Ext.define('Sisconsolid.controller.App', {
    extend: 'Sisconsolid.controller.Base',
    init: function() {
        this.listen({
            controller: {},
            component: {},
            global: {},
            store: {}  
        });
    },
	views: [
        'layout.Menu',
        'layout.Center',
        'layout.Landing'
    ],
    refs: [
        {
            ref: 'Menu',
            selector: '[xtype=layout.menu]'
        },
        {
            ref: 'CenterRegion',
            selector: '[xtype=layout.center]'
        }
    ],
	init: function() {
        this.listen({
            controller: {
                '#App': {
                    tokenchange: this.dispatch
                }
            },
            component: {
                'menu[xtype=layout.menu] menuitem': {
                    click: this.addHistory
                } 
            },
			global: {
				aftervalidateloggedin: this.setupApplication
			},
            store: {},
			proxy: {
				'#baserest': {
					requestcomplete: this.handleRESTResponse
				}
			}  
        });
    },
	/**
	 * Entry point for our application. Will render the viewport, and do any other setup required for our application
	 */
	setupApplication: function() {
		var me = this;
		// create the viewport, effectively creating the view for our application
		Ext.create( 'Sisconsolid.view.Viewport' );
		 // init Ext.util.History on app launch; if there is a hash in the url,
		// our controller will load the appropriate content
		Ext.util.History.init(function(){
			var hash = document.location.hash;
			me.fireEvent( 'tokenchange', hash.replace( '#', '' ) );
		})
		// add change handler for Ext.util.History; when a change in the token
		// occurs, this will fire our controller's event to load the appropriate content
		Ext.util.History.on( 'change', function( token ){
			me.fireEvent( 'tokenchange', token );
		});
	},
	/**
     * Add history token to Ext.util.History
     * @param {Ext.menu.Item} item
     * @param {Object} e
     * @params {Object} opts
     */
    addHistory: function( item, e, opts ) {
        var me = this,
            token = item.itemId;
        Ext.util.History.add( token );
        me.fireEvent( 'tokenchange', token )
    },
    /**
     * Handles token change and directs creation of content in center region
     * @param {String} token
     */
    dispatch: function( token ) {
        var me = this,
            config;
        // switch on token to determine which content to create
        switch( token ) {
            case translations.idmenuitemconsolidations:
                config = {
                    xtype: 'consolidation.list',
                    title: translations.consolidations,
					iconCls: 'icon_color'
                };
                break;
            case translations.idmenuitemconsolidators:
                config = {
                    xtype: 'consolidator.list',
                    title: translations.consolidators,
					iconCls: 'icon_color'
                };
                break;
			case translations.idmenuitemcells:
                config = {
                    xtype: 'cell.list',
                    title: translations.cells
                };
                break;
			case translations.idmenuitemreports:
                config = {
                    xtype: 'panel',
                    title: translations.reports
                };
                break;
            default: 
                config = {
                    xtype: 'layout.landing'
                };
                break;
        }
        me.updateCenterRegion( config );
    },
    /**
     * Updates center region of app with passed configuration
     * @param {Object} config
     */
    updateCenterRegion: function( config ) {
        var me = this,
            center = me.getCenterRegion();

        // remove all existing content
        center.removeAll( true );
        // add new content
        center.add( config );
    },
    /**
     * After a REST response is completed, this method will marshall the response data and inform other methods with relevant data
     * @param {Object} request
     * @param {Boolean} success The actual success of the AJAX request. For success of {@link Ext.data.Operation}, see success property of request.operation
     */
    handleRESTResponse: function( request, success ) {
        var me = this,
            rawData = request.proxy.reader.rawData;
        // in all cases, let's hide the body mask
        Ext.getBody().unmask();
        // if proxy success
        if( success ) {
            // if operation success
            if( request.operation.wasSuccessful() ) {

            }
            // if operation failure
            else {
                // switch on operation failure type
                switch( rawData.type ) {
                    case 'validation':
                        me.showValidationMessage( rawData.data, rawData.success, rawData.message, rawData.type );
                        break;
                }
            }
        }
        // otherwise, major failure...
        else {

        }
    },
    /**
     * Displays errors from JSON response and tries to mark offending fields as invalid
     * @param {Sisconsolid.proxy.Rest} proxy
     * @param {Array} data
     * @param {Boolean} success
     * @param {String} message
     * @param {String} type
     */
    showValidationMessage: function( data, success, message, type ) {
        var me = this,
            errorString = '<ul>';
        // looping over the errors
        for( var i in data ) {
            var error = data[ i ];
            errorString += '<li>' + eval('translations.' + error.message) + '</li>';
            // match form field with same field name
            var fieldMatch = Ext.ComponentQuery.query( 'field[name=' + error.field + ']' );
            // match?
            if( fieldMatch.length ) {
                // add extra validaiton message to the offending field
                fieldMatch[ 0 ].markInvalid(eval('translations.' + error.message));
            }
        }
        errorString += '</ul>';
        // display error messages in modal alert
        Ext.Msg.alert( eval('translations.' + message), errorString );
    }
});